//
// Maths.cpp for  in /home/goldbe_y//cpp/Maths/210random
//
// Made by yoni goldberg
// Login   <goldbe_y@epitech.net>
//
// Started on  Tue Jun 14 14:23:56 2011 yoni goldberg
// Last update Mon Jun 20 00:36:35 2011 leo faucon
//

#include <fstream>
#include <sstream>
#include <iostream>
#include "convert.hpp"
#include "Maths.hpp"


Maths::Maths() :
  Ox(),
  khi(0),
  nb(1000),
  borne_a(0),
  borne_b(10),
  table(NULL)
{
}

Maths::~Maths()
{
  size_t	j = 0;
  while (j < table.size())
    {
      table[j].erase(table[j].begin(), table[j].end());
      j++;
    }
  table.erase(table.begin(), table.end());
  Ox.clear();
}

int	Maths::readfile()
{
  std::ifstream	file("table.txt");

  if (file.is_open())
    {
      size_t	j = 0;
      size_t	i = 0;
      std::string	line;
      std::vector< std::string >	tmp;
      while (std::getline(file, line, '\t'))
	{
	  std::string	tmp2;
	  size_t found = line.find_last_of("\n");
	  if (found != std::string::npos)
	    tmp2 = line.substr(0, found).c_str();
	  else
	    tmp2.assign(line);
	  tmp.push_back(tmp2);
	  i++;
	  if (i == 12)
	    {
	      j++;
	      i = 0;
	      if (j != 31) table.push_back(tmp);
	      tmp.clear();
	    }
	}
      file.close();
    }
  else
    return (0);
  return (1);
}

std::string    Maths::calc(int _borne_a, int _borne_b, int _nb)
{
  borne_a = _borne_a;
  borne_b = _borne_b;
  nb = _nb;

  srand(time(NULL));
  Fill();
  Khi();

  size_t	i = 1;
  while (i < table[borne_b-borne_a-1].size()-1)
    {
      if (string_to_var<float>(table[borne_b-borne_a-1][i]) > khi)
	break;
      i++;
    }
  std::ostringstream res;
  res << "Resultat : khi = " << khi  << " compris entre : " << table[0][i]
      << "% et " << table[0][i-1] << "%";

  return (res.str());
}

  void		Maths::Fill()
  {
    int	temp[borne_b];
    for (int i = 0; i < borne_b; ++i) temp[i] = 0;
    for (int i = 0; i < nb; ++i) temp[(rand() % borne_b) + borne_a]++;
    for (int i = 0; i < borne_b; i++) Ox.push_back(temp[i]);
  }

  void		Maths::Khi()
  {
    khi = 0;
    for (int i = 0; i < borne_b; ++i)
      {
	int	temp = pow((Ox[i] - (nb/(borne_b - borne_a))), 2);
	khi += temp;
      }
    khi /= 100;
  }
